#include "netprinter.h"

NetPrinter::NetPrinter(QObject *parent)
    : PrinterClient(parent) {
    m_socket = new QTcpSocket(this);
    m_timeoutTimer = new QTimer(this);
    m_timeoutTimer->setSingleShot(true);

    connect(m_socket, &QTcpSocket::connected, this, &NetPrinter::onConnected);
    connect(m_socket, &QTcpSocket::bytesWritten, this, &NetPrinter::onBytesWritten);
    connect(m_socket, &QTcpSocket::disconnected, this, &NetPrinter::onDisconnected);
    connect(m_socket, &QTcpSocket::errorOccurred, this, &NetPrinter::onError);
    connect(m_timeoutTimer, &QTimer::timeout, this, &NetPrinter::onTimeout);
}

void NetPrinter::sendData(const QByteArray& data) {
    if (m_socket->state() != QAbstractSocket::UnconnectedState) {
        emit errorOccurred("打印机忙，请等待当前操作完成");
        return;
    }

    m_data = data;
    m_bytesWritten = 0;
    qDebug() << "发送打印连接……";
    m_socket->connectToHost(ip, port, QIODevice::WriteOnly, QAbstractSocket::IPv4Protocol);
    m_timeoutTimer->start(8000); // 8秒连接超时
}

void NetPrinter::writeNextChunk() {
    qDebug() << "写入数据。。。";
    const qint64 chunkSize = 4096; // 4KB分片
    QByteArray chunk = m_data.mid(m_bytesWritten, chunkSize);
    qint64 written = m_socket->write(chunk);

    if (written == -1) {
        emit errorOccurred(QString("数据发送失败: %1").arg(m_socket->errorString()));
        m_socket->disconnectFromHost();
    }
}

void NetPrinter::cleanup() {
    m_timeoutTimer->stop();
    m_data.clear();
    m_bytesWritten = 0;
}

void NetPrinter::onConnected() {
    qDebug() << "连接完成";
    m_timeoutTimer->stop();
    m_timeoutTimer->start(15000); // 15秒发送超时
    m_socket->setSocketOption(QAbstractSocket::LowDelayOption, 1);
    writeNextChunk();
}

void NetPrinter::onBytesWritten(qint64 bytes) {
    m_bytesWritten += bytes;
    if (m_bytesWritten < m_data.size()) {
        writeNextChunk();
    } else {
        m_socket->disconnectFromHost();
    }
}

void NetPrinter::onDisconnected() {
    if (m_bytesWritten == m_data.size()) {
        emit dataSent();
    }
    cleanup();
}

void NetPrinter::onError(QAbstractSocket::SocketError error) {
    QString msg = QString("网络错误: %1 (%2)").arg(m_socket->errorString()).arg(error);
    emit errorOccurred(msg);
    cleanup();
}

void NetPrinter::onTimeout() {
    emit errorOccurred("操作超时");
    m_socket->abort();
    cleanup();
}
